package cn.pku.sirx.snad.ads.strategy.impl;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;

import cn.pku.sirx.snad.ad.domain.BusinessKeywordTable;
import cn.pku.sirx.snad.ad.model.UserContext;
import cn.pku.sirx.snad.ad.model.WeightedKeyword;
import cn.pku.sirx.snad.ads.strategy.IKeywordRetrievalStrategy;
import cn.pku.sirx.snad.ads.wordsegmentation.IKAnalyzerImpl;
import cn.pku.sirx.snad.ads.wordsegmentation.IWordSegmentation;
import cn.pku.sirx.snad.ads.wordsegmentation.WordSegmentationException;

/**
 * @author WangXiao
 */
public class KeywordRetrievalStrategyImpl implements IKeywordRetrievalStrategy {

	@Override
	public List<WeightedKeyword> retrieveKeywords(UserContext userContext) {
		Assert.notNull(userContext);

		/*
		 * word segmentation
		 */
		Map<String, int[]> wordMap = new HashMap<String, int[]>();
		segmentation(userContext.getSummary(), wordMap, 0);
		segmentation(userContext.getTitle(), wordMap, 10);
		/*
		 * convert to weighted keyword
		 */
		List<WeightedKeyword> result = new LinkedList<WeightedKeyword>();
		for (String keyword : wordMap.keySet()) {
			WeightedKeyword weightedKeyword = new WeightedKeyword();
			weightedKeyword.setKeyWord(keyword);
			int[] value = wordMap.get(keyword);
			weightedKeyword.setWeight(value[0] * value[1]);
			result.add(weightedKeyword);
		}
		return result;
	}

	private void segmentation(String sentences, Map<String, int[]> wordMap,
			int weightPlus) {
		try {
			List<String> words = wordSegmentation.segmentWords(sentences);
			for (String word : words) {
				int[] value = wordMap.get(word); // value: {count, weight}
				if (value == null) {
					Integer weight = BusinessKeywordTable.getWeight(word);
					if (weight != null) { // ignore those not in table
						value = new int[] { 1 + weightPlus, weight };
						wordMap.put(word, value);
					}
				} else {
					value[0] += 1 + weightPlus * 2;
				}
			}
		} catch (WordSegmentationException e) {
			LOG.error(e);
		}
	}

	private IWordSegmentation wordSegmentation = new IKAnalyzerImpl();

	private static final Log LOG = LogFactory
			.getLog(KeywordReorderStrategyImpl.class);

}
